package com.koalac.ironman.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.util.Base64;

import com.koalac.ironman.cache.SysAppConfig;
import com.koalac.ironman.cache.SysAppConfig.DirName;

public class StringUtils {
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str) || str.equals("null")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 生成照片的文件路径
	 * 
	 * @return
	 */
	public static String generatePhotoFileName(Context context) {
		String fileName = UUID.getUpperCaseUUID() + ".jpg";
		String fileDir = SysAppConfig.getInstance().getDirByName(context,
				DirName.upoadHome);
		return fileDir + File.separator + fileName;
	}

	/**
	 * 将Map容器类型，转换为字符串，方便输出调试
	 * 
	 * @param map
	 * @return
	 */
	public static String getFormatedMap(Map<String, String> map) {
		return StringUtils.getFormatedMap("", map);
	}

	/**
	 * 将Map容器类型，转换为字符串，方便输出调试
	 * 
	 * @param map
	 * @return
	 */
	public static String getFormatedMap(String tips, Map<String, String> map) {
		String formatedStr = "";
		if (null == tips || tips.length() < 1) {
			formatedStr = "{";
		} else {
			formatedStr = tips + ":{";
		}
		if (null == map) {
			return formatedStr + "}.";
		}
		for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
			String key = it.next();
			String value = map.get(key);
			// 如对象的属性未初始化，默认为空字符串
			if (value == null) {
				value = "";
			}
			formatedStr += key + ":" + "\"" + value + "\"";
			if (it.hasNext()) {
				formatedStr += ",";
			} else {
				break;
			}
		}
		return formatedStr + "}.";
	}

	/**
	 * 将实例对象的属性转换为字符串，方便输出调试
	 * 
	 * @param map
	 * @return
	 */
	public static String getFormatedClass(String tips, Object instance) {
		String formatedStr = "";
		if (null == tips || tips.length() < 1) {
			formatedStr = "{";
		} else {
			formatedStr = tips + ":{";
		}

		Class<?> clz = instance.getClass();
		Field fields[] = clz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			fields[i].setAccessible(true);
			String key = fields[i].getName();
			try {
				formatedStr += key + ":" + "\"" + fields[i].get(instance)
						+ "\"";
				if (i < fields.length - 1) {
					formatedStr += ",";
				} else {
					break;
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

		}
		return formatedStr + "}.";
	}

	/**
	 * BASE64编码，URL Safe
	 * 
	 * @param value
	 * @return
	 */
	@SuppressLint("NewApi")
	public static String base64EncodeUrlSafe(String value) {
		if (value == null) {
			return null;
		}

		byte[] valueData = value.getBytes(CharsetUints.UTF_8);
		String tmp = Base64.encodeToString(valueData, Base64.URL_SAFE);
		valueData = null;
		return tmp;
	}

	/**
	 * BASE64解码，URL Safe
	 * 
	 * @param value
	 * @return
	 */
	@SuppressLint("NewApi")
	public static String base64DecodeUrlSafe(String value) {
		if (value == null || value.length() == 0) {
			return null;
		}
		byte[] valueData = value.getBytes(CharsetUints.UTF_8);
		if (valueData == null)
			return "";
		byte[] data = Base64.decode(valueData, Base64.URL_SAFE);
		if (data == null)
			return "";
		String string = new String(data, CharsetUints.UTF_8);
		valueData = null;
		data = null;
		return string;
	}

	/**
	 * 
	 * @param str
	 * @return
	 * @description 防止Android版本字符串判断问题
	 * @Date 2013 2013-3-25
	 * @author chenzf
	 */
	public static final boolean isNullOrEmpty(String str) {
		if (str == null)
			return true;
		if (str.trim().equals(""))
			return true;
		return false;
	}

	/**
	 * 
	 * @param str
	 * @return
	 * @description 是否是邮箱
	 * @Date 2013 2013-3-25
	 * @author chenzf
	 */
	public static final boolean isEmail(String str) {
		String str1 = "\\w+@(\\w+.)+[a-z]{2,4}";
		Pattern p1 = Pattern.compile(str1);
		Matcher m = p1.matcher(str);
		boolean isEmail = m.matches();
		return isEmail;
	}

	/**
	 * 
	 * @param str
	 * @return
	 * @description 是否为移动手机电话
	 * @Date 2013 2013-3-25
	 * @author chenzf
	 */
	public static final boolean isMobilePhone(String str) {
//		Pattern p1 = Pattern
//				.compile("^((13[0-9])|(14[0-9])|(17[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
//		boolean isMobile = p1.matcher(str).matches();
//		return isMobile;
		return !isEmpty(str) && str.length() == 11;
	}


	/*
	 * 判断是否为整数
	 * 
	 * @param str 传入的字符串
	 * 
	 * @return 是整数返回true,否则返回false
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	/*
	 * 判断是否为浮点数，包括double和float
	 * 
	 * @param str 传入的字符串
	 * 
	 * @return 是浮点数返回true,否则返回false
	 */
	public static boolean isDouble(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
		return pattern.matcher(str).matches();
	}

	private static HashMap<String, String> htmlEntities;
	static {
		htmlEntities = new HashMap<String, String>();
		htmlEntities.put("&lt;", "<");
		htmlEntities.put("&gt;", ">");
		htmlEntities.put("&amp;", "&");
		htmlEntities.put("&quot;", "\"");
		htmlEntities.put("&agrave;", "?");
		htmlEntities.put("&Agrave;", "?");
		htmlEntities.put("&acirc;", "?");
		htmlEntities.put("&auml;", "?");
		htmlEntities.put("&Auml;", "?");
		htmlEntities.put("&Acirc;", "?");
		htmlEntities.put("&aring;", "?");
		htmlEntities.put("&Aring;", "?");
		htmlEntities.put("&aelig;", "?");
		htmlEntities.put("&AElig;", "?");
		htmlEntities.put("&ccedil;", "?");
		htmlEntities.put("&Ccedil;", "?");
		htmlEntities.put("&eacute;", "?");
		htmlEntities.put("&Eacute;", "?");
		htmlEntities.put("&egrave;", "?");
		htmlEntities.put("&Egrave;", "?");
		htmlEntities.put("&ecirc;", "?");
		htmlEntities.put("&Ecirc;", "?");
		htmlEntities.put("&euml;", "?");
		htmlEntities.put("&Euml;", "?");
		htmlEntities.put("&iuml;", "?");
		htmlEntities.put("&Iuml;", "?");
		htmlEntities.put("&ocirc;", "?");
		htmlEntities.put("&Ocirc;", "?");
		htmlEntities.put("&ouml;", "?");
		htmlEntities.put("&Ouml;", "?");
		htmlEntities.put("&oslash;", "?");
		htmlEntities.put("&Oslash;", "?");
		htmlEntities.put("&szlig;", "?");
		htmlEntities.put("&ugrave;", "?");
		htmlEntities.put("&Ugrave;", "?");
		htmlEntities.put("&ucirc;", "?");
		htmlEntities.put("&Ucirc;", "?");
		htmlEntities.put("&uuml;", "?");
		htmlEntities.put("&Uuml;", "?");
		htmlEntities.put("&nbsp;", " ");
		htmlEntities.put("&copy;", "\u00a9");
		htmlEntities.put("&reg;", "\u00ae");
		htmlEntities.put("&euro;", "\u20a0");
		htmlEntities.put("&apos;", "'");
		htmlEntities.put("&mdash;", "-");
	}

	public static String unescapeHTML(String input) {
		StringBuilder builder = new StringBuilder();
		int pos = 0;
		int c = input.indexOf('&', pos);

		while (c != -1) {
			builder.append(input.substring(pos, c));
			int posEndToken = input.indexOf(';', c);
			if (posEndToken != -1) {
				posEndToken++;
				String token = input.substring(c, posEndToken);
				String unescapeToken = htmlEntities.get(token);
				if (unescapeToken != null) {
					builder.append(unescapeToken);
				} else {
					builder.append(input.substring(pos, posEndToken));
				}
				pos = posEndToken;
			} else {
				pos = c;
				builder.append(input.charAt(pos));
				pos++;
			}
			c = input.indexOf('&', pos);
		}

		builder.append(input.substring(pos));

		return builder.toString();
	}

	public static String getSha1Hash(String input) throws Exception {
		String retval = null;
		ByteArrayInputStream inputStream = new ByteArrayInputStream(
				input.getBytes("UTF-8"));
		MessageDigest hash = MessageDigest.getInstance("SHA1");
		byte[] buffer = new byte[1024];

		int numRead = 0;
		while ((numRead = inputStream.read(buffer)) != -1) {
			hash.update(buffer, 0, numRead);
		}

		retval = toHexString(hash.digest());
		return retval;

	}

	protected static final byte[] Hexhars = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String toHexString(byte[] input) {
		StringBuilder buf = new StringBuilder(2 * input.length);
		for (int i = 0; i < input.length; i++) {
			int v = input[i] & 0xff;
			buf.append((char) Hexhars[v >> 4]);
			buf.append((char) Hexhars[v & 0xf]);
		}
		return buf.toString();
	}

	public static String loadRawResourceString(Resources res, int resourceId)
			throws IOException {
		StringBuilder builder = new StringBuilder();
		InputStream is = res.openRawResource(resourceId);
		InputStreamReader reader = new InputStreamReader(is);
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			builder.append(buf, 0, numRead);
		}
		return builder.toString();

	}

	public static String elipse(String input, int numMaxChar) {
		if (input.length() >= numMaxChar - 3) {
			String retval = input.substring(0, numMaxChar);
			retval += "...";
			return retval;
		} else {
			return input;
		}
	}

	public static String replaceAll(String input, String regex, String value) {
		return input.replaceAll(regex,
				value == null ? "" : Matcher.quoteReplacement(value));
	}

	/**
	 * @author huifeng.xu 说明：汉字长度2,字符长度1; 汉字的处理：半个汉字均去除;
	 * @param str
	 *            待处理字符串
	 * @param start
	 *            处理的首位置
	 * @param length
	 *            长度
	 * @param more
	 *            省略符号
	 * @return String
	 */
	public static String getSubString(String str, int start, int length) {
		length += start;
		int len = 0;
		StringBuffer sb = new StringBuffer();
		String resStr = "";
		int k = 0;
		while (len < length && k < str.length()) {
			char c = str.charAt(k++);
			if (c > 255) {
				len += 2;
				if (len > length)
					break;
			} else {
				len += 1;
			}
			sb.append(c);
			if (len == start || len == start + 1) {
				resStr = sb.toString();
			}
		}
		if (k == str.length()) {
			return sb.toString().replaceFirst(resStr, "");
		}
		return sb.toString().replaceFirst(resStr, "") + "...";
	}

	// 默认时间格式
	public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static final String MDHM_DATE_PATTERN = "MM月dd日 HH:mm";
	public static final String YMD_DATE_PATTERN = "yyyy-MM-dd";

	/**
	 * 字符串转为时间
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static Date string2Date(String date, String pattern) {
		SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
		Date d = null;
		try {
			if (date == null || "".equals(date))
				return new Date();
			d = format.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			d = new Date();
		}
		return d;
	}

	/**
	 * 字符串转为时间
	 * 
	 * @param date
	 * @return
	 */
	public static Date string2Date(String date) {
		return string2Date(date, DEFAULT_DATE_PATTERN);
	}

	/**
	 * 时间戳转时间
	 * 
	 * @param timestamp
	 * @return
	 */
	public static String timestamp2String(String timestamp) {
		String dateString = null;
		SimpleDateFormat sdf = new SimpleDateFormat(MDHM_DATE_PATTERN);
		long timeStampValue = Long.valueOf(timestamp);
		dateString = sdf.format(new Date(timeStampValue * 1000L));
		return dateString;
	}

	/**
	 * 时间戳转时间
	 * 
	 * @param timestamp
	 * @return
	 */
	public static String timestamp2String(String timestamp, String pattern) {
		String dateString = null;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		long timeStampValue = Long.valueOf(timestamp);
		dateString = sdf.format(new Date(timeStampValue * 1000L));
		return dateString;
	}

	/**
	 * 时间转为字符串
	 * 
	 * @param date
	 * @return yyyy-MM-dd HH:mm:ss格式
	 */
	public static String date2String(Date date) {
		if (date == null)
			return null;
		SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_PATTERN,
				Locale.US);
		formatter.setTimeZone(TimeZone.getDefault());
		return formatter.format(date);
	}

	/**
	 * 判断是否是中文字符
	 * 
	 * @param c
	 * @return
	 */
	public static boolean isChineseChar(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
			return true;
		}
		return false;
	}

	/**
	 * 将字符串中的中文转化为拼音,其他字符不变
	 *
	 * @param inputString
	 * @return
	 */
	public static String string2Pingyin(String inputString) {
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);

		char[] input = inputString.trim().toCharArray();
		String output = "";

		try {
			for (int i = 0; i < input.length; i++) {
				// 判断该字符是不是中文
				if (java.lang.Character.toString(input[i]).matches(
						"[\\u4E00-\\u9FA5]+")) {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(
							input[i], format);
					output += temp[0];
				} else
					output += java.lang.Character.toString(input[i]);
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return output;
	}

	public static Timestamp string2Timestamp(String timeStamp) {
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		ts = Timestamp.valueOf(timeStamp);
		ts.setSeconds(ts.getSeconds() / 1000);
		return ts;
	}

}
